<template>
  <lay-form-item v-if="inputValue!=undefined">
    <lay-col md="8">
      <span>
        <lay-avatar :src="userInfoStore.systemInfo.siteUrl + inputValue" class="preview"></lay-avatar>
      </span>
    </lay-col>
  </lay-form-item>
  <lay-form-item :label="uplabel" prop="imgurl">
    <lay-col md="8">
      <span>
        <lay-input v-model="inputValue" style="width:98%"></lay-input>
      </span>
    </lay-col>
    <lay-col md="8">
      <lay-upload @done="getUploadFile" :url="uploadConfig.uploadUrl" field="File" :data="uploadConfig.uploadImages"
        :size="fileSize" :headers="uploadConfig.uploadHeaders" acceptMime="image/png, image/jpeg">
        <template v-slot:default="params">
          <lay-button type="normal">上传</lay-button>
        </template>
      </lay-upload>
      <span class="tip"> 尺寸：{{userInfoStore.systemInfo.imageSize}} kb 类型： {{userInfoStore.systemInfo.imageExt}}</span>
    </lay-col>
  </lay-form-item>
</template>

<script lang="ts">
import { defineComponent, ref, watch, defineEmits, computed } from "vue";
export default defineComponent({
  name: "UploadImg",
})
</script>
  
<script lang="ts" setup>
import { uploadConfig } from "../../api/upload"
import { layer } from "@layui/layer-vue";
import { useUserStore } from "../../store/user";

const userInfoStore = useUserStore();

interface UploadProps {
  modelValue?: string | undefined,
  // 大小限制(KB)
  fileSize: number,
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  //fileType: Array<String>,
  uplabel: string
}
const emit = defineEmits(["update:modelValue"])
const props = withDefaults(defineProps<UploadProps>(), {
  modelValue: undefined,
  fileSize: 500,
  uplabel: "上传图片"
  //fileType: () => ['png', 'jpg', 'jpeg'],
});

const fileSize = ref(props.fileSize)
const uplabel = ref(props.uplabel)

const inputValue = computed({
  get: () => props.modelValue || '',
  set: val => {
    emit('update:modelValue', val)
  }
})

const getUploadFile = (res: any) => {
  let up = JSON.parse(res.data)
  if (up.status == 1) {
    layer.msg(up.msg)
    emit('update:modelValue', up.data.url)
  } else {
    layer.msg(up.error)
  }
};

// const before = (file: any) => {
//   console.log("beginChoose", file);
//   let isImg = false
//   if (props.fileType.length) {
//     let fileExtension = ''
//     if (file.name.lastIndexOf('.') > -1) {
//       fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
//     }
//     isImg = props.fileType.some((type) => {
//       if (file.type.indexOf(type) > -1) return true
//       if (fileExtension && fileExtension.indexOf(type) > -1) return true
//       return false
//     })
//   } else {
//     isImg = file.type.indexOf('image') > -1
//   }
//   if (!isImg) {
//     layer.msg(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`)
//     return false
//   }
// };


</script>

<style scoped>
.tip {
  color: gray;
  line-height: 30px;
  height: 30px;
  padding-left: 10px;
}

.preview {
  width: 120px;
  height: 80px;
}
</style>